package aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class AioServer implements CompletionHandler<AsynchronousSocketChannel, Object> {


    private AsynchronousServerSocketChannel serverSocketChannel;

    public void start() throws IOException {

        this.serverSocketChannel = AsynchronousServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        serverSocketChannel.accept(null, this);

    }

    @Override
    public void completed(AsynchronousSocketChannel result, Object attachment) {
        try {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName());
                    while (true) {
                        System.out.println("开始=" + result);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
                        Integer read = result.read(byteBuffer).get();
                        byte[] b = new byte[read];
                        byte[] src = byteBuffer.array();
                        for (int i = 0; i < read; i++) {
                            b[i] = src[i];
                        }
                        System.out.println(new String(b));
                        Thread.sleep(10000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }).start();
        } finally {
            this.serverSocketChannel.accept(null, this);
        }
    }

    @Override
    public void failed(Throwable exc, Object attachment) {

    }

    public static void main(String[] args) throws IOException {
        AioServer server = new AioServer();

        server.start();

        System.in.read();

    }
}
